package com.news.yp.baselibrary.navigationbottom;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.news.yp.baselibrary.navigationbottom.iterator.TabItertor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :yp
 * @date :2018/9/13
 * @gmail:yinpeng6868@gmail.com
 * @Description: 自定义一个底部的导航栏 ，里面的资源靠动态加载进去，这样的话可以实现更换底部样式的作用。
 */
public class NavigationBottom extends LinearLayout {

    private List<BottomTabItem> mTabTiems;
    private int mCurrentIndex = -1;

    public NavigationBottom(Context context) {
        this(context, null);
    }

    public NavigationBottom(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NavigationBottom(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(HORIZONTAL);
        mTabTiems = new ArrayList<>();
    }

    public void addTabItem(TabItertor tabItertor) {
        mTabTiems.clear();
        int index = 0;
        while (tabItertor.hasNext()) {
            BottomTabItem next = tabItertor.next();
            View tabView = next.getTabView();
            addView(tabView);
            LinearLayout.LayoutParams params = (LayoutParams) tabView.getLayoutParams();
            params.weight = 1;
            params.gravity = Gravity.CENTER;
            tabView.setLayoutParams(params);
            //给条目设置点击事件，等等
            setItemClickListener(tabView, index++);
            mTabTiems.add(next);
        }
        mTabTiems.get(0).setSelected(true);
        mCurrentIndex = 0;
    }

    BottomSelectListener bottomSelectListener;

    public void setSelectListener(BottomSelectListener bottomSelectListener) {
        this.bottomSelectListener = bottomSelectListener;
    }

    private void setItemClickListener(View tabView, final int i) {
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentIndex != i) {
                    //原来的设置成非选中
                    mTabTiems.get(mCurrentIndex).setSelected(false);
                    //把当前设置成选中
                    mCurrentIndex = i;
                    mTabTiems.get(mCurrentIndex).setSelected(true);

                    //把点击事件接口暴露出去，被人使用
                    bottomSelectListener.selectBottom(i);
                }
            }
        });
    }
}
